import { webSocket, WebSocketSubject } from "rxjs/webSocket";
import { delay, filter } from "rxjs/operators";
import appConfig from "~/config/app.config";
import { Observable } from "rxjs";

export default class CallSocketService {
  public static callCenterSocket: WebSocketSubject<any>;
  public static readonly HEARTBEAT_DURTION = 10;

  /**
   *
   * ^((?!WsktHeatbeat).)*$
   *
   * socket 过滤
   */

  public static initSocket() {
    if (!this.callCenterSocket) {
      // this.callCenterSocket = webSocket(appConfig.callCenter.socket);
      this.callCenterSocket = webSocket('ws://218.78.89.124:9010/apws');
      this.start();
    }
  }

  public static onDisConnect() {
    return new Observable(subscriber => {
      this.callCenterSocket.subscribe({
        error: () => {
          subscriber.next()
        },
        complete:() =>{
          subscriber.complete()
        }
      });
    });
  }

  public static destory() {
    if (!this.callCenterSocket.isStopped) {
      this.callCenterSocket.complete();
      this.callCenterSocket.observers.forEach(x => x.complete());
    }
  }

  /**
   * 发送心跳数据
   */
  private static sendHeartbeat() {
    this.callCenterSocket.next({
      methodName: "WsktHeatbeat"
    });
  }

  private static start() {
    if (this.callCenterSocket.hasError) return;
    if (this.callCenterSocket.observers.length > 0) return;
    this.callCenterSocket
      .pipe(
        filter(res => res.methodName === "WsktHeatbeat"),
        delay(this.HEARTBEAT_DURTION * 1000)
      )
      .subscribe(this.sendHeartbeat.bind(this));

    this.sendHeartbeat();
  }
}
